package db;

import java.util.List;

import server.Statistics;

import entities.Location;
import entities.Message;

public abstract class MessageDAO {
	protected static MessageDAO instance = null;
	protected Statistics stats;
	
	protected abstract void dbConnect();
	protected abstract void dbCloseConnection();
	
	protected abstract void dbAddMessage(Message message);
	protected abstract List<Message> dbGetMessagesForRecipientLocation(int recipientId, Location location);
	
	protected abstract List<Message> dbGetAllMessages();
	
	protected abstract void dbClearDatabase();
	
	public MessageDAO(){
		stats = Statistics.getInstance();
	}
	
	public synchronized void connect() {
		dbConnect();
	}
	
	public synchronized void closeConnection() {
		dbCloseConnection();
	}
	
	public synchronized void addMessage(Message message) {
		long startTime = System.currentTimeMillis();
		dbAddMessage(message);
		long endTime = System.currentTimeMillis();
		stats.logDbSend(endTime - startTime);
	}
	
	public synchronized List<Message> getMessagesForRecipientLocation(int recipientId, Location location) {
		long startTime = System.currentTimeMillis();
		List<Message> list = dbGetMessagesForRecipientLocation(recipientId, location);
		long endTime = System.currentTimeMillis();
		stats.logDbPoll(endTime - startTime);
		return list;
	}
	
	public synchronized List<Message> getAllMessages() {
		return dbGetAllMessages();
	}
	
	public synchronized void clearDatabase() {
		dbClearDatabase();
	}
}
